<template>
  <div class="amap">
    <!-- 地图容器 -->
    <div ref="amap" class="amap_view"></div>
    <!-- 搜索栏 -->
    <el-input
      id="map_input"
      v-model.trim="searchVal"
      placeholder="请输入关键字"
      size="small"
    ></el-input>
  </div>
</template>

<script>
import AMapLoader from "@amap/amap-jsapi-loader";

export default {
  data() {
    return {
      amap: null,
      searchVal: "",
      map: null,
      AMap: null,
      AMapLoader: null,
    };
  },
  mounted() {
    this.loadAMap();
  },
  beforeDestroy() {
    if (this.map) {
      this.map.destroy();
      this.map = null;
    }
  },
  methods: {
    loadAMap() {
      this.AMapLoader.load({
        key: "e5761f5df1d30e2ffedee67d693ff590",
        version: "2.0",
        plugins: ["AMap.Scale", "AMap.ToolBar"],
      })
        .then((AMap) => {
          this.AMap = AMap;
          this.initMap();
        })
        .catch((e) => {
          console.error(e);
        });
    },
    initMap() {
      this.map = new this.AMap.Map(this.$refs.amap, {
        resizeEnable: true,
        zooms: [1, 18],
        zoom: 14,
      });

      // 比例尺
      this.map.addControl(new this.AMap.Scale());
      // 工具条
      this.map.addControl(new this.AMap.ToolBar());

      // 标记
      let maker = new this.AMap.Marker({
        title: "长安街1号",
        position: this.map.getCenter(),
      });
      this.map.add(maker);

      // 关键字搜索
      let auto = new this.AMap.AutoComplete({ input: "map_input" });
      let placeSearch = new this.AMap.PlaceSearch({ map: this.map });
      auto.on("select", (e) => {
        placeSearch.setCity(e.poi.adcode);
        placeSearch.search(e.poi.name);
      });
    },
  },
};
</script>

<style scoped>
.amap {
  width: 100%;
  height: calc(100vh - 284px);
  border: 1px solid #ccc;
  position: relative;

  .amap_view {
    width: 100%;
    height: 100%;
  }
  .el-input {
    width: 256px;
    position: absolute;
    top: 10px;
    right: 10px;
  }
}
</style>